package com.walkline.screen;

import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.CheckboxField;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.component.ObjectChoiceField;
import net.rim.device.api.ui.container.MainScreen;

import com.walkline.util.sqlite.Currency;
import com.walkline.util.sqlite.SQLManager;
import com.walkline.util.ui.ForegroundManager;

public class SettingsCurrencyScreen extends MainScreen
{
	private SQLManager _sqlManager;
	private ForegroundManager _foreground = new ForegroundManager(0);

	private ObjectChoiceField _choiceCurrencyID;
	private EditField _showAsChinese;
	private EditField _showAsAbbreviation;
	private EditField _showAsSymbol;
	private CheckboxField _defaultItem;

	public SettingsCurrencyScreen(SQLManager sqlManager)
	{
		super(NO_VERTICAL_SCROLL | USE_ALL_HEIGHT | NO_SYSTEM_MENU_ITEMS);

		setTitle("Currency Settings");

		_sqlManager = sqlManager;

		_choiceCurrencyID = new ObjectChoiceField("IDs: ", null, 0) {
			protected void fieldChangeNotify(int context)
			{
				if (context != FieldChangeListener.PROGRAMMATIC)
				{
					queryFirstRecorderDetails();
				}
			};
		};
		_showAsChinese = new EditField("Show as Chinese: ", null, EditField.DEFAULT_MAXCHARS, EditField.USE_ALL_WIDTH);
		_showAsAbbreviation = new EditField("Show as abbreviation: ", null, EditField.DEFAULT_MAXCHARS, EditField.USE_ALL_WIDTH);
		_showAsSymbol = new EditField("Show as symbol: ", null, EditField.DEFAULT_MAXCHARS, EditField.USE_ALL_WIDTH);
		_defaultItem = new CheckboxField("Default", false);

		_foreground.add(_choiceCurrencyID);
		_foreground.add(_showAsChinese);
		_foreground.add(_showAsAbbreviation);
		_foreground.add(_showAsSymbol);
		_foreground.add(_defaultItem);
        add(_foreground);

        UiApplication.getUiApplication().invokeLater(new Runnable()
        {
			public void run()
			{
				String[] _currencies = _sqlManager.getCurrenciesID();
				_choiceCurrencyID.setChoices(_currencies);

				queryFirstRecorderDetails();
			}
		});
	}

	private void queryFirstRecorderDetails()
	{
		String currentID = _choiceCurrencyID.getChoice(_choiceCurrencyID.getSelectedIndex()).toString();

		if (!currentID.equalsIgnoreCase("none"))
		{
			Currency currency = _sqlManager.getCurrencyByID(Integer.parseInt(currentID));

			if (currency != null)
			{
				_showAsChinese.setText(currency.getChinese());
				_showAsAbbreviation.setText(currency.getAbbreviation());
				_showAsSymbol.setText(currency.getSymbol());
				_defaultItem.setChecked(currency.isDefault());
			}
		}
	}
}